package com.jinduplan.planmanager.ui.activity

import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.text.TextUtils
import android.util.Log
import com.baidu.mapapi.SDKInitializer
import com.cxz.kotlin.baselibs.base.BaseMvpActivity
import com.cxz.kotlin.baselibs.utils.LogUtil
import com.cxz.kotlin.baselibs.utils.StatusBarUtil
import com.jinduplan.planmanager.bean.Tab_Bean
import com.jinduplan.planmanager.mvp.contract.MainContract
import com.jinduplan.planmanager.mvp.presenter.MainPresenter
import com.jinduplan.planmanager.ui.fragment.MainFragment
import com.jinduplan.planmanager.ui.fragment.MineFragment
import com.jinduplan.planmanager.utils.DialogUtil
import com.jinduplan.planmanager.utils.ResUtil
import kotlinx.android.synthetic.main.activity_main.*
import androidx.fragment.app.Fragment
import com.cxz.kotlin.baselibs.rx.bus.BusEvent
import com.cxz.kotlin.baselibs.rx.bus.RxBus
import com.jinduplan.planmanager.R
import com.jinduplan.planmanager.app.App
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import kotlinx.android.synthetic.main.fragment_main.*


class MainActivity : BaseMvpActivity<MainContract.View, MainContract.Presenter>(),
    MainContract.View {

    private var tabs: ArrayList<Tab_Bean>? = null

    private val mDialog by lazy {
        DialogUtil.getWaitDialog(this, "正在加载")
    }

    val mReceiver: BroadcastReceiver by lazy {
        object : BroadcastReceiver() {
            override fun onReceive(context: Context, intent: Intent) {
                val action = intent.action
                if (TextUtils.isEmpty(action)) {
                    return
                }
                var text = ""
                var needShow = true
                if (action == SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR) {
                    text = ("key 验证出错! 错误码 :" + intent.getIntExtra(
                        SDKInitializer.SDK_BROADTCAST_INTENT_EXTRA_INFO_KEY_ERROR_CODE,
                        0
                    )
                            + " ; 请在 AndroidManifest.xml 文件中检查 key 设置")
                } else if (action == SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_OK) {
                    text = "key 验证成功! 功能可以正常使用"
                    needShow = false
                } else if (action == SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR) {
                    text = "网络出错"
                }
                (tabs?.get(0)?.fragment as MainFragment).setErrorInfo(text,needShow)
                LogUtil.d("SDKReceiver->$text")
            }
        }

    }


    override fun createPresenter(): MainContract.Presenter = MainPresenter()


    override fun showLoading() {
        mDialog.show()
    }

    override fun hideLoading() {
        mDialog.dismiss()
    }

    override fun attachLayoutRes(): Int {
        return R.layout.activity_main
    }

    override fun onBackPressed() {
        doubleClickExit(this)
    }

    override fun start() {

        // 注册 SDK 广播监听者
        val iFilter = IntentFilter()
        iFilter.addAction(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_OK)
        iFilter.addAction(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR)
        iFilter.addAction(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR)
        registerReceiver(mReceiver, iFilter)
    }

    override fun initView() {
        super.initView()
        needShowLoading = false
        StatusBarUtil.setLightMode(this)
        StatusBarUtil.setColor(this, ResUtil.getC(R.color.bg_bur), 0)
        tabs = ArrayList()
        var tab1 = Tab_Bean(
            ResUtil.getS(R.string.tab_main),
            R.mipmap.home_0,
            R.mipmap.home_1,
            0,
            MainFragment.newInstance()
        )

        var tab2 = Tab_Bean(
            ResUtil.getS(R.string.tab_mine),
            R.mipmap.user_0,
            R.mipmap.user_1,
            0,
            MineFragment.newInstance()
        )
        tabs?.add(tab1)
        tabs?.add(tab2)
        tabLayout.setMenus(tabs, this)
        tabLayout.setOnTabClickListener {
            when (it) {
                0 -> {
                    Log.e("tab", "首页")
                    StatusBarUtil.setLightMode(this)
                    StatusBarUtil.setColor(this, ResUtil.getC(R.color.bg_bur), 0)
                }
                1 -> {
                    Log.e("tab", "个人")
                    StatusBarUtil.setDarkMode(this)
                    StatusBarUtil.setColor(this, ResUtil.getC(R.color.deep_blue_jdy), 0)
                }

            }
            //更新tabs
            tabLayout.updateMenu(tabs, it)
        }
        tabLayout.updateMenu(tabs, 0)
        requestLocationPermission({}, {
            (tabs?.get(0)?.fragment as MainFragment).isFirstLoc = true
        }, { (tabs?.get(0)?.fragment as MainFragment).locationStart() })


        RxBus.get().toFlowable(BusEvent.LoginEvent::class.java)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                App.handler.postDelayed({
                    if (it.isLogin) {
                        showMain()
                        (tabs?.get(0)?.fragment as MainFragment).requestLocation()

                    }
                },100)

            }
    }

    fun showMain() {
        LogUtil.d("showMain!!!!")
        StatusBarUtil.setLightMode(this)
        StatusBarUtil.setColor(this, ResUtil.getC(R.color.bg_bur), 0)
        tabLayout.updateMenu(tabs, 0)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        Log.e("onActivityResult","$resultCode"+" "+"$requestCode"+" "+data?.getStringExtra("project_name"))
        when (requestCode) {
            1 -> if (resultCode == Activity.RESULT_OK) {

                (tabs?.get(0)?.fragment as MainFragment).onActivityResult(
                    1,
                    Activity.RESULT_OK,
                    data
                )
            }

        }
        super.onActivityResult(requestCode, resultCode, data)


    }

    override fun onDestroy() {
        super.onDestroy()
        // 取消监听 SDK 广播
        unregisterReceiver(mReceiver)
    }


}
